import {createElement} from "./createElement";
import {updateChild} from "./updateChild";

export const patchVnode = (oldNode, newNode) => {
    //节点相同直接返回
    if (oldNode === newNode) return;
    //判断新节点是否有text属性
    if (newNode.text !== undefined && (newNode.children === undefined || newNode.children.length === 0)) {
        if (newNode.text === oldNode.text) return;
        if (oldNode.elm) {
            oldNode.elm.innerText = newNode.text;
            //******************//
            // newNode.elm = oldNode.elm;
        }
    } else {
        if (Array.isArray(oldNode.children) && oldNode.children.length > 0) {
            //diff算法
            console.log('diff对比')
            updateChild(oldNode.elm,oldNode.children,newNode.children)
        } else {
            //清空dom 文本信息
            oldNode.elm.innerText = '';
            const fragment = new DocumentFragment();
            for (let i = 0; i < newNode.children.length; i++) {
                let dom = createElement(newNode.children[i]);
                fragment.appendChild(dom);
            }
            oldNode.elm.appendChild(fragment);
            //****************************//
            // newNode.elm = oldNode.elm;
        }
    }
    newNode.elm = oldNode.elm
}